
using System;
using System.Text;
using System.Web.Security;
using System.Collections.Generic;

using Grr;
using Grr.Web;
using Grr.Models;

using Grr.Web.WebControls;
using Castle.MonoRail.Framework.Views.Aspx;

public partial class Views_Grurrah_grurrah : GrurrahViewPage, IGrurrahPage
{
    private static readonly string RatingsScriptUrl = "~/Content/scripts/ratings-control.js";

    protected override string TabName
    {
        get { return "explore"; }
    }
    protected override void OnPreRender(EventArgs e)
    {
        Page.ClientScript.RegisterClientScriptInclude("ratings-control", ResolveUrl(RatingsScriptUrl));
        base.OnPreRender(e);
    }

    public long Id
    {
        get
        {
            object o = ViewState["Id"];
            if (o == null)
                return -1;
            return (long)o;
        }
        set
        {
            ViewState["Id"] = value;
        }
    }

    public string Name
    {
        get
        {
            string name = (string) ViewState["Name"];
            if (name == null)
                return String.Empty;
            return name;
        }
        set
        {
            ViewState["Name"] = value;
        }
    }

    public string Text
    {
        get
        {
            string text = (string)ViewState["Text"];
            if (text == null)
                return String.Empty;
            return text;
        }
        set
        {
            ViewState["Text"] = value;
        }
    }

    public string CreatorName
    {
        get
        {
            string text = (string)ViewState["CreatorName"];
            if (text == null)
                return "Anonymous";
            return text;
        }
        set
        {
            ViewState["CreatorName"] = value;
        }
    }

    public int Rating
    {
        get
        {
            object o = ViewState["Rating"];
            if (o == null)
                return 0;
            return (int)o;
        }
        set
        {
            ViewState["Rating"] = value;
        }
    }

    public UserGrurrahStatus UserStatus
    {
        get
        {
            object o = ViewState["UserStatus"];
            if (o == null)
                return UserGrurrahStatus.None;
            return (UserGrurrahStatus)o;
        }
        set
        {
            ViewState["UserStatus"] = value;
        }
    }

    public string TagsStr
    {
        get
        {
            string tags = (string)ViewState["TagsStr"];
            if (tags == null)
                return String.Empty;
            return tags;
        }
        set
        {
            ViewState["TagsStr"] = value;
        }
    }
    // Add a local 'cache' for when we are enumerating,
    // so we avoid all the conversion overhead
    private string[] tags;

    public string [] Tags
    {
        get
        {
            if (tags != null)
                return tags;
            string tags_str = (string) ViewState["TagsStr"];
            if (tags_str == null) {
                tags = new string [0];
                return tags;
            }
            tags = TagsStrToArray(tags_str);
            return tags;
        }
        set
        {
            tags = value;
            TagsStr = TagsAsString(value);
        }
    }

    protected override void SetProperties()
    {
        Grurrah grurrah = (Grurrah)PropertyBag["grurrah"];
        Id = grurrah.Id;
        Name = grurrah.Name;
        Text = grurrah.Text;
        Rating = grurrah.Rating;
        Tags = grurrah.Tags;
        CreatorName = grurrah.CreatorName;
        UserStatus = grurrah.UserStatus;

        SetupRatings();
    }

    public override void OnUserLoggedIn(MembershipUser user)
    {
        UserGrurrahStatus status = Grurrah.StatusForUser(Id, user);
        SetUserStatus(status);
    }

    public override void OnUserLoggedOut()
    {
        SetUserStatus (UserGrurrahStatus.None);
    }

    private void SetUserStatus(UserGrurrahStatus status)
    {
        if (UserStatus == status)
            return;

        UserStatus = status;
        UserStatusView.ActiveViewIndex = (int)status;
        UserStatusView.ForceAnUpdate();
    }

    private void SetupRatings()
    {
        RatingAverageHiddenField.Value = Rating.ToString(System.Globalization.CultureInfo.InvariantCulture);
    }

    private void SubmitRating(int rating)
    {
        MembershipUser user = Membership.GetUser();

        if (user == null)
        {
            NotifyUser ("Sorry, you need to be logged in to rate Grurrahs.");
            return;
        }
        
        Grurrah.SubmitRating(Id, user, rating);
        ClearRatingButton.Visible = true;
        RatingLockedHiddenField.Value = "true";
    }

    private void ClearRating()
    {
        MembershipUser user = Membership.GetUser();
        if (user == null)
        {
            NotifyUser ("Sorry, you need to be logged in to rate Grurrahs.");
            return;
        }

        Grurrah.ClearRating(Id, user);
        ClearRatingButton.Visible = false;
        RatingLockedHiddenField.Value = "false";
    }

    protected void RatingStar1_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        SubmitRating(1);
    }
    protected void RatingStar2_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        SubmitRating(2);
    }
    protected void RatingStar3_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        SubmitRating(3);
    }
    protected void RatingStar4_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        SubmitRating(4);
    }
    protected void RatingStar5_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        SubmitRating(5);
    }
    protected void ClearRatingButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        ClearRating();
    }
    protected void EditTagsButton_Click(object sender, EventArgs e)
    {
        EditTagsTextBox.Text = TagsStr;
        TagsView.ActiveViewIndex = 1;
        TagsView.ForceAnUpdate();
    }
    protected void EditTagsDoneButton_Click(object sender, EventArgs e)
    {
        string[] tainted_tags = TagsStrToArray(EditTagsTextBox.Text);
        List<string> tags = new List<string>(tainted_tags.Length);

        foreach (string tainted_tag in tainted_tags)
        {
            string t = tainted_tag.Trim();
            if (Validator.IsValidTagName(t))
                tags.Add(t);
        }

        Grurrah.SetTags(Id, tags, new List<string> (Tags));
        
        Tags = tags.ToArray();
        TagsView.ActiveViewIndex = 0;
        TagsView.ForceAnUpdate();
    }

    private string[] TagsStrToArray(string tags_str)
    {
        string[] tags = tags_str.Split(new char [] { ',' });

        for (int i = 0; i < tags.Length; i++)
            tags[i] = tags[i].TrimStart();
        return tags;
    }

    private string TagsAsString(string [] tags)
    {
        StringBuilder str = new StringBuilder();

        for (int i = 0; i < tags.Length; i++)
        {
            str.Append(tags[i]);
            if (i < tags.Length - 1)
                str.Append(", ");
        }

        return str.ToString();
    }
    
    protected void SwitchToEditButton_Click(object sender, EventArgs e)
    {
        FCKeditor1.Value = Text;
        ModeView.ActiveViewIndex = 1;
        ModeView.ForceAnUpdate();
    }
    
    protected void CancelEditButton_Click(object sender, EventArgs e)
    {
        ModeView.ActiveViewIndex = 0;
        ModeView.ForceAnUpdate();
    }
    protected void SaveEditButton_Click(object sender, EventArgs e)
    {
        string tainted_text = FCKeditor1.Value;

        Text = Grurrah.UpdateDescriptionText(Id, tainted_text);
       
        ModeView.ActiveViewIndex = 0;
        ModeView.ForceAnUpdate();
    }

    private void NotifyUser (string notification)
    {
        UserNotificationLabel.Text = notification;
        user_notification_window.Visible = true;
    }
    protected void UserNoticationCloseButton_Click(object sender, EventArgs e)
    {
        user_notification_window.Visible = false;
    }
    protected void NoneViewWantToDoItButton_Click(object sender, EventArgs e)
    {
        MembershipUser user = Membership.GetUser();

        if (user == null)
        {
            NotifyUser("Sorry, if you want Grurrah to remember what you are doing, you need to be logged in.");
            return;
        }

        Grurrah.SetStatusForUser(Id, user, UserGrurrahStatus.WantToDoIt);
        SetUserStatus(UserGrurrahStatus.WantToDoIt);
    }

    protected void DoingItButton_Click(object sender, EventArgs e)
    {
        MembershipUser user = Membership.GetUser();

        if (user == null)
        {
            NotifyUser("Sorry, if you want Grurrah to remember what you are doing, you need to be logged in.");
            return;
        }

        Grurrah.SetStatusForUser(Id, user, UserGrurrahStatus.DoingIt);
        SetUserStatus(UserGrurrahStatus.DoingIt);
    }

    protected void NotDoingItButton_Click(object sender, EventArgs e)
    {
        MembershipUser user = Membership.GetUser();

        if (user == null)
        {
            NotifyUser("Sorry, if you want Grurrah to remember what you are doing, you need to be logged in.");
            return;
        }

        Grurrah.SetStatusForUser(Id, user, UserGrurrahStatus.None);
        SetUserStatus(UserGrurrahStatus.None);
    }
}
